package com.zengdada.authority.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.zengdada.authority.exception.RoutineException;
import com.zengdada.authority.model.DynamicPage;
import com.zengdada.authority.model.DynamicPageTableRel;
import com.zengdada.authority.service.DynamicPageAuthorityService;
import com.zengdada.authority.service.DynamicPageTableRelAuthorityService;
import com.zengdada.authority.utils.CommonUtils;
import com.zengdada.authority.utils.JsonMessage;
import com.zengdada.authority.utils.mapper.Page;
import com.zengdada.authority.utils.mapper.Sort;
import com.zengdada.authority.utils.transformdata.TransformDataClobToString;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import static com.zengdada.authority.utils.JsonMessage.fail;
import static com.zengdada.authority.utils.JsonMessage.success;

/**
 * @Auther: 12614
 * @Contact: 1261438511@qq.com
 * @Date: 2019/3/9 14:13
 * @Description:
 */
@Controller
@RequestMapping("/authority/dynamic_page")
public class DynamicPageAuthorityController {

    ObjectMapper objectMapper = new ObjectMapper();


    @Autowired
    @Qualifier("dynamicPageAuthorityServiceImpl")
    DynamicPageAuthorityService dynamicPageAuthorityService;

    @Autowired
    @Qualifier("dynamicPageTableRelAuthorityServiceImpl")
    DynamicPageTableRelAuthorityService dynamicPageTableRelAuthorityService;

    @GetMapping(value = "/list.html")
    public String listPage(HttpServletRequest request) {
        request.setAttribute("title", "动态页面 管理");
        return "authority/dynamic/page/list";
    }

    @PostMapping(value = "/list.do")
    @ResponseBody
    public JsonMessage list(@RequestParam(value = "searchs", required = false) String searchs, Page page, Sort sort) {
        try {
            PageInfo<Map<String, Object>> pageInfo = dynamicPageAuthorityService.selectDetailedPageInfoByParam(searchs, page, sort);
            return success(CommonUtils.depthTransformDataType(pageInfo.getList(), Collections.singletonList(new TransformDataClobToString())), pageInfo.getTotal());
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }

    @GetMapping(value = "/edit.html")
    public String edit(HttpServletRequest request, String id) {
        request.setAttribute("id", id);
        request.setAttribute("title", StringUtils.isBlank(id) ? "动态页面 新增" : "动态页面 编辑");
        return "authority/dynamic/page/edit";
    }

    @PostMapping(value = "/save.do")
    @ResponseBody
    public JsonMessage save(DynamicPage dynamicPage) {
        try {
            if (dynamicPageAuthorityService.save(dynamicPage) > 0)
                return success();
            else throw new Exception("未修改任何数据（1.权限不足；2.非本应用数据；3.数据不存在）");
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }

    @PostMapping(value = "/detail/{id}.do")
    @ResponseBody
    public JsonMessage detail(@PathVariable(value = "id") String id) {
        try {
            return success(dynamicPageAuthorityService.selectById(id));
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }


    @PostMapping(value = "/del.do")
    @ResponseBody
    public JsonMessage del(@RequestParam(value = "id") String id) {
        try {
            if (dynamicPageAuthorityService.deleteById(id) > 0)
                return success();
            else throw new Exception("未删除任何数据（1.权限不足；2.非本应用数据；3.数据不存在）");
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }

    // --------------表格-----------------


    @GetMapping(value = "/table/list.html")
    public String tableListPage(HttpServletRequest request, String pageId) {
        if (StringUtils.isBlank(pageId)) throw new RoutineException("异常请求！！");
        request.setAttribute("title", "表格管理");
        request.setAttribute("pageId", pageId);
        return "authority/dynamic/page/table/list";
    }

    @GetMapping(value = "/table/edit.html")
    public String tableEdit(HttpServletRequest request, String id, String pageId) {
        request.setAttribute("tableId", id);
        request.setAttribute("pageId", pageId);
        request.setAttribute("title", StringUtils.isBlank(id) ? "表格 新增" : "表格 编辑");
        return "authority/dynamic/page/table/edit";
    }

    @PostMapping(value = "/table/detail.do")
    @ResponseBody
    public JsonMessage tableDetail(DynamicPageTableRel dynamicPageTableRel) {
        try {
            return success(dynamicPageTableRelAuthorityService.selectById(dynamicPageTableRel));
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }

    @PostMapping(value = "/table/save.do")
    @ResponseBody
    public JsonMessage tableSave(DynamicPageTableRel dynamicPageTableRel) {
        try {
            if (dynamicPageTableRelAuthorityService.selectById(dynamicPageTableRel) == null)
                dynamicPageTableRelAuthorityService.add(dynamicPageTableRel);
            else
                dynamicPageTableRelAuthorityService.updateById(dynamicPageTableRel);
            return success();
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }


    @PostMapping(value = "/table/del.do")
    @ResponseBody
    public JsonMessage tableDel(DynamicPageTableRel dynamicPageTableRel) {
        try {
            return success(dynamicPageTableRelAuthorityService.deleteById(dynamicPageTableRel));
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }


// --------------页面-----------------


    @GetMapping(value = "/simple_list.html")
    public String simple_list(HttpServletRequest request, @RequestParam("pageId") String pageId) throws JsonProcessingException {
        Map<String, Object> data = dynamicPageAuthorityService.createPageData(pageId);
        request.setAttribute("title", ((DynamicPage) data.get("page")).getTitle());
        String config = objectMapper.writeValueAsString(data.get("config"));
        request.setAttribute("config", config);
        return "authority/dynamic/page/public_simple_list";
    }

    @GetMapping(value = "/simple_table.html")
    public String simple_table(HttpServletRequest request, @RequestParam("tableId") String tableId) throws JsonProcessingException {
        List<Map<String, Object>> data = dynamicPageAuthorityService.createPageDataByTableId(tableId);
        request.setAttribute("title", data.get(0).get("title"));
        String config = objectMapper.writeValueAsString(data);
        request.setAttribute("config", config);
        return "authority/dynamic/page/public_simple_list";
    }
}
